<?php

namespace PhalApi\DingComBot;

class Lite
{


    private $config;
    static private $instance = null;

    /**
     * 构造方法
     * @param $config
     */
    function __construct($config)
    {
        if (is_array($config)) {
            $this->config = $config;
            $this->AppSecret = isset($config['AppSecret']) ? $config['AppSecret'] : null;
        } else {
            $this->config = array();
        }
    }

    /**
     *克隆方法私有化
     */
    function __clone()
    {
        // TODO:Implement __clone() methed.
    }

    /**
     * 获取当前实例
     * @param array $config
     * @return null|Lite
     */
    static public function getInstance($config)
    {
        //判断$instance是否是Singleton的对象，不是则创建
        if (!self::$instance instanceof self) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }

    /**
     * 服务端消息处理
     */
    public function Server($ServerClass = '')
    {

        if (empty($ServerClass)) $ServerClass = '\\' . __NAMESPACE__ . '\\Server';
        $msg = json_decode(file_get_contents('php://input'), TRUE);
        $postHeader = $this->getHeader();
        $AppSecret = $this->AppSecret;
        $localtime = $this->getLocalTime();
        $Str = $postHeader['TIMESTAMP'] . "\n" . $AppSecret;
        $signStr = base64_encode(hash_hmac('sha256', $Str, $AppSecret, true));
        if ($signStr == $postHeader['SIGN'] && abs($localtime - $postHeader['TIMESTAMP']) < 1200000) {
            $api = new $ServerClass();
            if (!empty($msg["msgtype"])) {
                $func = $msg["msgtype"];
                $api->$func($msg);

            }
        } else {
            \PhalApi\DI()->ddBot->Text('非法请求' . json_encode($postHeader) . json_encode($msg));
        }
    }

    public function getHeader()
    {
        $headers = array();
        foreach ($_SERVER as $key => $value) {
            if ('HTTP_' == substr($key, 0, 5)) {
                $headers[str_replace('_', '-', substr($key, 5))] = $value;
            }
            if (isset($_SERVER['PHP_AUTH_DIGEST'])) {
                $header['AUTHORIZATION'] = $_SERVER['PHP_AUTH_DIGEST'];
            } elseif (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
                $header['AUTHORIZATION'] = base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW']);
            }
            if (isset($_SERVER['CONTENT_LENGTH'])) {
                $header['CONTENT-LENGTH'] = $_SERVER['CONTENT_LENGTH'];
            }
            if (isset($_SERVER['CONTENT_TYPE'])) {
                $header['CONTENT-TYPE'] = $_SERVER['CONTENT_TYPE'];
            }
        }
        return $headers;
    }

    /**
     * 获取本地毫秒时间戳
     * @return float
     */
    public function getLocalTime()
    {
        list($s1, $s2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
    }
}
